package com.kuaiditu.assistant.api.zzt_api;

import com.alibaba.fastjson.JSON;
import com.kuaiditu.assistant.api.ParamsAnalog;
import com.kuaiditu.assistant.api.xz_api.xz_encode.xz_http.FormBodyBuilderFactory;
import com.kuaiditu.assistant.api.zzt_api.base.BaseZTResponse;
import com.kuaiditu.assistant.api.zzt_api.zzt_encode.DataDigestUtil;
import com.kuaiditu.assistant.entity.Operator;
import com.kuaiditu.assistant.module.retrofit.FastJsonConverterFactory;
import com.kuaiditu.assistant.module.retrofit.impl.ZTConverterAdapter;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import io.reactivex.Observable;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by Eenie on 2017/8/11.
 * Email: eeniework@gmail.com
 * Des:
 */

public class ZZTApi {
    private ZZTService mZZTService;
    private final int DEFUALT_TIME = 10;



    private SimpleDateFormat mSimpleDateFormat;


    private ParamsAnalog mParamsAnalog;




    public ZZTApi(ParamsAnalog paramsAnalog) {
        mParamsAnalog = paramsAnalog;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(DEFUALT_TIME, TimeUnit.SECONDS)
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();

        mZZTService = new Retrofit.Builder()
                .baseUrl("https://zztgateway.zto.com")
                .client(client)
                .addConverterFactory(FastJsonConverterFactory.create(new ZTConverterAdapter()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(ZZTService.class);


        mSimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }


    public Observable<BaseZTResponse> addAcceptExpress(String express, Operator operator) {


//        String data = "{\"scanData\":[{\"pdaScanData\":{\"billCode\":\"762197878520\",\"date\":\"20170814125157\",\"empCode\":\"02179.008\",\"fenjianCode\":\"\",\"\":\"04\"},\"index\":0}]}";

        Map<String, Object> params = new HashMap<>();
        List expressList = new ArrayList();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> scanData = new HashMap<>();
        scanData.put("billCode", express);
        scanData.put("date", mSimpleDateFormat.format(System.currentTimeMillis()));
        scanData.put("empCode", operator.getZt_empCode());
        scanData.put("fenjianCode", "");
        scanData.put("type", "04");
        data.put("index", 0);
        data.put("pdaScanData", scanData);
        expressList.add(data);
        params.put("scanData", expressList);
        return mZZTService.fetchData(operator.getZt_token(), operator.getZt_openId(), FormBodyBuilderFactory.createZTBody("SCAN_UPLOAD", params, operator));
    }



    public Observable<ResponseBody> login(String token,String openId) {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("msg_type", "INFO_USER");
        builder.add("data", "[]");
        builder.add("company_id", "APP_ANDROID");
        builder.add("data_digest", DataDigestUtil.digest(JSON.toJSONString("[]"), token, "UTF-8"));
        builder.add("open_id", openId);
        builder.add("version", "4.1.0");
        builder.add("timestamp", String.valueOf(System.currentTimeMillis()));

        return mZZTService.ReqData(token, openId, builder.build());
    }



    public Observable<BaseZTResponse> addSignExpress(String express,Operator operator) {
//        {"scanData":[{"pdaScanData":{"billCode":"453123204617","date":"20170915172521","empCode":"02104.089","latitude":"31.208269","longitude":"121.478685","signType":"本人","type":"05"},"index":0}]}
        Map<String, Object> params = new HashMap<>();
        List expressList = new ArrayList();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> scanData = new HashMap<>();
        scanData.put("billCode", express);
        scanData.put("date", mSimpleDateFormat.format(System.currentTimeMillis()));
        scanData.put("empCode", operator.getZt_empCode());
        scanData.put("latitude", mParamsAnalog.getDevice_lat());
        scanData.put("longitude", mParamsAnalog.getDevice_lng());
        scanData.put("signType", "本人");
        scanData.put("type", "05");
        data.put("index", 0);
        data.put("pdaScanData", scanData);
        expressList.add(data);
        params.put("scanData", expressList);
        return mZZTService.fetchData(operator.getZt_token(), operator.getZt_openId(), FormBodyBuilderFactory.createZTBody("SCAN_UPLOAD", params, operator));
    }


    public Observable<ResponseBody> refreshToken(Operator operator) {
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "refresh_token");
        params.put("refresh_token", operator.getZt_refresh_token());
        return mZZTService.refreshToken("https://connect.zto.com/oauth2/token", params);
    }
}
